package com.cn.client.util;

import com.cn.api.OrderCoreService;
import com.cn.api.StockService;
import com.cn.dto.OrderDTO;
import com.cn.dto.StockDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @program: SpringCloud
 * @description: redis Key过期监听
 * @author: zhang yi
 * @create: 2020-03-24 14:14
 */
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OrderCoreService orderCoreService;
    @Autowired
    private StockService stockService;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("过期key:" + message.toString());
        String str = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        System.out.println(str);
        try {
            // 从失效key中筛选代表订单失效的key
            String key = message.toString();
            OrderDTO orderDTO = orderCoreService.findByOrderNumber(key);
            String status = orderDTO.getOrderStatus();
            StockDTO stockDTO=new StockDTO();
            stockDTO.setPriceId(orderDTO.getProductId());
            stockDTO.setAvailableStock(orderDTO.getVisitorNumber());
            if (key != null && status.equals("待付款")) {
                // 查询订单，如果是未支付状态则为-取消订单
                orderCoreService.updateStatusCancel(key);
                //返回库存
                stockService.add(stockDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}